//
//  DrugListViewController.m
//  MedicineBox
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "DrugListViewController.h"
#import "ListCollectionViewCell.h"
#import "AsyncConnection.h"
#import "Define.h"
#import "HomeModel.h"
#import "DrugDetailViewController.h"

#import "MJRefreshAutoNormalFooter.h"
#import "MJRefreshNormalHeader.h"

#import "DKNightVersion.h"
#import "UIImageView+NightImage.h"
@interface DrugListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, retain) NSMutableArray *collectArray;
@property (nonatomic, retain) UICollectionView *collect;

@property (nonatomic, assign) NSInteger i;
@end



@implementation DrugListViewController

-(void)dealloc
{
    [_collectArray release];
    [_collect release];
    
    [super dealloc];
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
    [self handleData];
    [self createNavigation];
    [self createCollectionView];
}

#pragma mark -
#pragma mark 设置导航栏
- (void)createNavigation
{
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    navView .backgroundColor = [UIColor colorWithRed:86/255.0 green:137/255.0 blue:156/255.0 alpha:1];
    navView.nightBackgroundColor = UIColorFromRGB(0x444444);
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 63, self.view.frame.size.width, 0.5)];
    line.backgroundColor = [UIColor whiteColor];
    [navView addSubview:line];
    [self.view addSubview:navView];
    [navView release];

    
//标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 30, 100, 30)];
    titleLabel.text = @"药品列表";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:86/255.0 green:137/255.0 blue:156/255.0 alpha:1];

    titleLabel.font = [UIFont fontWithName:@"Baskerville-SemiBold" size:20];

    titleLabel.nightTextColor = [UIColor whiteColor];
    [navView addSubview:titleLabel];
    [titleLabel release];
//返回
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10 , 30, 60, 30)];
    [navView addSubview:backButton];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [backButton release];
    
}

- (void)buttonAction:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 
#pragma mark 数据处理

- (void)handleData
{
    self.word = [self.word stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"app" forKey:@"app_key"];
    [dic setObject:@"0" forKey:@"curPage"];
    [dic setObject:@"20" forKey:@"limit"];
    [dic setObject:@"9DFAAD5404FCB6168EA6840DCDFF39E5" forKey:@"sign"];
    [dic setObject:self.word forKey:@"word"];
    [dic setObject:@"" forKey:@"tags"];

    [AsyncConnection asyncConnectionWithUrl:MB_DrugList name:self.word parameters:dic block:^(id data) {
    
       NSArray *list = [[data objectForKey:@"results"] objectForKey:@"List"];
       for (NSDictionary *dic in list) {
           HomeModel *model = [[HomeModel alloc] init];
           [model setValuesForKeysWithDictionary:dic];
           [self.collectArray addObject:model];
       }
       [self.collect reloadData];
        
   } get:@"get"];
    
}

#pragma mark -
#pragma mark 创建collectView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width , self.view.frame.size.height - 64) collectionViewLayout:layout];
    self.collect.backgroundColor = [UIColor clearColor];
    self.collect.delegate = self;
    self.collect.dataSource = self;
    self.collect.nightBackgroundColor = UIColorFromRGB(0x343434);
    //注册重用池中所放置的cell类型
    [self.collect registerClass:[ListCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:self.collect];
    [_collect release];
    [layout release];
    
    [self createRefresh];
}
#pragma mark -
#pragma mark 刷新加载
- (void)createRefresh
{
    self.i = 1;
    
//刷新
    self.collect.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.collect.header beginRefreshing];
        [self handleData];
        [self.collect.header endRefreshing];
    }];
//加载
    self.collect.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        NSString *page = [NSString stringWithFormat:@"%ld",_i * 20];
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:@"app" forKey:@"app_key"];
        [dic setObject:page forKey:@"curPage"];
        [dic setObject:@"20" forKey:@"limit"];
        [dic setObject:@"9DFAAD5404FCB6168EA6840DCDFF39E5&tags" forKey:@"sign"];
        [dic setObject:self.word forKey:@"word"];
        [AsyncConnection asyncConnectionWithUrl:MB_DrugList name:self.word parameters:dic block:^(id data) {
            NSArray *list = [[data objectForKey:@"results"] objectForKey:@"List"];
            for (NSDictionary *dic in list) {
                HomeModel *model = [[HomeModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.collectArray addObject:model];
            }
            [self.collect reloadData];
            [self.collect.footer endRefreshing];
        } get:@"get"];
        self.i++;
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectArray.count;
    
}
#pragma mark -
#pragma mark 自定义cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    ListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (self.collectArray.count > 0) {
        
        [cell valueWithModel:[self.collectArray objectAtIndex:indexPath.item]];
    }
    return cell;
}

//设定每个item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.view.frame.size.width - 50) / 2, 200);
}

#pragma mark -
#pragma mark 点击item进入药品详情

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DrugDetailViewController *detail = [[DrugDetailViewController alloc] init];
    detail.deatilId = [[self.collectArray objectAtIndex:indexPath.item] _id];
    detail.namecn = [[self.collectArray objectAtIndex:indexPath.item] namecn];
    [self presentViewController:detail animated:YES completion:nil];
    [detail release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
